﻿
package extremefx.anim {
	import extremefx.events.EventHandler;
	
	import flash.display.Shape;
	import flash.events.Event;
	import flash.utils.getTimer;		

	/**
	 * @author Marcelo Volmaro
	 */
	public final class FrameEventDispatcher {
		private static var _inst:FrameEventDispatcher;
		
		private var _shape:Shape;
		private var _list:Vector.<Number>;
		private var _arg:TickEventArgs;
		
		public static var position:Number;
	
		public function FrameEventDispatcher(pRes:PrivateClass):void {
			position = getTimer()/1000;
			
			_shape = new Shape();
			_shape.addEventListener(Event.ENTER_FRAME, _tick);
			_arg = new TickEventArgs(0);
			_list = Vector.<Number>([position, position]);
		}
		
		private static function get _instance():FrameEventDispatcher{
			if (_inst == null){
				_inst = new FrameEventDispatcher(new PrivateClass());
			}
			
			return _inst;
		}
		
		private function _tick(evt:Event):void {
			var pos:Number = getTimer()/1000, _len:int;
			if (_list.length > 60) _list.shift();
			_list[(_len = _list.length)] = pos;
			
			position += (pos - _list[0]) / (_len - 1);
			_arg.position = position;
			 
			if (_eOnTick) _eOnTick.fire(_arg);
		}
		
		public static function get onTick():EventHandler {
			return _instance._getOnTick();
		}
		
		private var _eOnTick:EventHandler;
		private function _getOnTick():EventHandler{
			if (_eOnTick == null) _eOnTick = new EventHandler(this);
			return _eOnTick;
		}
	}
}

final class PrivateClass {}
